// 拖动音频，音量
new store.Slider('music-slider');
new store.Slider('volume-slider');

var musicList = document.getElementById('musicList');//歌曲div
var tbody = musicList.getElementsByTagName('tbody')[0]; // 歌曲列表
var music_detail = musicList.getElementsByClassName('music-right')[0]; // 详细信息
var poster = music_detail.getElementsByClassName('poster'); 

var checkall = document.getElementById('checkall'); // 全选
var checks = tbody.getElementsByTagName('input'); // 单选
var song_del_one = tbody.getElementsByClassName('music-left-song-del'); // 删除单个
var del_check = document.getElementById('del-check'); // 删除多个选中

var clear_list = document.getElementById('clear-list'); // 清空列表

var song_tool_play = tbody.getElementsByClassName('song-tool-play');// list播放

/* 播放控制 */
var play_ctrls = document.getElementById('play-ctrls');
var prev = play_ctrls.getElementsByClassName('prev')[0];// 上一曲
var next = play_ctrls.getElementsByClassName('next')[0];// 下一曲
var play = play_ctrls.getElementsByClassName('play')[0];// 播放

var music_cur = play_ctrls.getElementsByClassName('music-cur')[0]; // 歌曲信息

var audio = document.getElementById('audio');// 播放器


var music_slider = document.getElementById('music-slider');// 音乐进度条
var music_plan = music_slider.getElementsByClassName('plan')[0]; // 音乐进度
var music_slider_btn = music_slider.getElementsByClassName('slider_btn')[0];//音乐拖动按钮

var volume_slider = document.getElementById('volume-slider'); // 音量进度条
var volume_plan = volume_slider.getElementsByClassName('plan')[0]; // 音量进度
var volume_slider_btn = volume_slider.getElementsByClassName('slider_btn')[0];//音量拖动按钮

var mask_pic = document.getElementsByClassName('mask-pic'); // mask图层

var play_list = play_ctrls.getElementsByClassName('play-list')[0];//播放顺序

var playOrder = ['0 -205px','0 -232px','0 -257px','0 -72px'];// 播放顺序
var playOrderIndex = 0;// 播放顺序索引

var collect = play_ctrls.getElementsByClassName('collect')[0];//点击红心

var state = play_ctrls.getElementsByClassName('state')[0];//纯净模式

var volume_icon = play_ctrls.getElementsByClassName('volume-icon')[0];//音量图标

var now = 0;// 当前播放列表下标

var volmue_size = 1;//当前音量大小

// 渲染歌曲
store.ajax({

    url : './json/music.json',

    success : function(res){

        var arr = JSON.parse(res);
        // 获取每个音频时长，渲染列表
        loding(arr);
        
    }
})

// 获取每个音频时长，渲染列表
function loding(arr){   


    var len = arr.length;

    var count = 0;
    
    var timer = null;

    tbodyLoding();

    function tbodyLoding(){

        audio.src = arr[count].src;

        timer = setInterval(srcTime,100)

    }
    // 加载list
    function srcTime(){

        if(audio.readyState == 4){

            var audioDuration = store.doubleNum(parseInt(audio.duration / 60)) + ':' + store.doubleNum(parseInt(audio.duration % 60));

            tbody.innerHTML += `<tr data-src='${arr[count].src}' data-pic='${arr[count].pic}' data-singer='${arr[count].singer}' data-song='${arr[count].song}'>
                                <td><input type="checkbox"></td>
                                <td>${count+1}</td>
                                <td>
                                    ${arr[count].song}
                                    <div class="music-left-song-tool">
                                        <a href="#" class="song-tool-play"></a>
                                        <a href="#" class="song-tool-add"></a>
                                        <a href="#" class="song-tool-share"></a>
                                    </div>
                                </td>
                                <td>${arr[count].singer}</td>
                                <td>
                                    <time>${audioDuration}</time>
                                    <a href="#" class="music-left-song-del"></a>
                                </td>
                                
                            </tr>`;

            count++;

            clearInterval(timer);

            if(count < len){

                tbodyLoding();

            }else{
                console.log('加载完成');

                audio.src = tbody.children[now].getAttribute('data-src');

                // 刷新预览图片，信息
                resPic();

                // mask背景
                maskBg();

                // 全选，单选
                checkFn();
                // 删除单个
                song_del();

                // 播放时间，进度条
                timeUpDate();
                
                // list列表点击播放
                listPlay();
            }
        }else{
            console.log('加载中');
        }
    }
    
}
// 加载详细图片，信息
function resPic(){

    var t = tbody.children;


    music_detail.innerHTML = `<div class="poster"></div>
                                <p>歌曲名：<i>${t[now].getAttribute('data-song')}</i></p>
                                <p>歌手名：<i>${t[now].getAttribute('data-singer')}</i></p>
                                <p>专辑名：<i>${t[now].getAttribute('data-song')}</i></p>`;
    poster[0].style.backgroundImage = `url(${t[now].getAttribute('data-pic')})`;
    
    // 控制条歌曲信息
    music_cur.innerHTML = `<p>
                            <a href="#">${t[now].getAttribute('data-song')}</a>
                            <i>-</i>
                            <a href="#">${t[now].getAttribute('data-singer')}</a>
                        </p>
                        <div class="music-cur-time">
                            <time>00:00</time>
                            /
                            <time></time>
                        </div>`
}

// 播放时间，进度条
function timeUpDate(){

    var t = tbody.children;

    var playTime = music_cur.getElementsByTagName('time')[0]; //已播放时长
    var totalTime = music_cur.getElementsByTagName('time')[1]; // 总时长

    audio.oncanplay = function(){

        var audioDuration = store.doubleNum(parseInt(audio.duration / 60)) + ':' + store.doubleNum(parseInt(audio.duration % 60));

        totalTime.innerHTML = audioDuration;
        
    }

    audio.ontimeupdate = function(){
            
        var current = store.doubleNum(parseInt(audio.currentTime / 60)) + ':' + store.doubleNum(parseInt(audio.currentTime % 60));

        playTime.innerHTML = current;

        var scale = audio.currentTime / audio.duration;

        var w = scale * (music_slider.offsetWidth - music_slider_btn.offsetWidth);

        music_slider_btn.style.left = w + 'px';

        music_plan.style.width = w + 'px'; 

    }

}

// 时间跳转
store.bindEvent(music_slider,'mouseup',function(e){

    var e = e || event;
    
    sliderClick.call(this,e);

    var time = music_plan.offsetWidth / (music_slider.offsetWidth - music_slider_btn.offsetWidth) * audio.duration;

    audio.currentTime = time;

})

// 音量跳转
store.bindEvent(volume_slider,'click',function(e){

    var e = e || event;

    sliderClick.call(this,e);

    var vol = volume_plan.offsetWidth / (volume_slider.offsetWidth - volume_slider_btn.offsetWidth);

    audio.volume =  vol;

})

// 音频，音量点击跳转left值
function sliderClick(e){
    var e = e || event;
    
    var target = e.target || e.srcElement;

    if(target.className == 'slider_btn') return;

    var slider_btn = this.getElementsByClassName('slider_btn')[0];// 进度条按钮
    
    var plan = this.getElementsByClassName('plan')[0];// 进度

    var l = e.clientX - store.getOffset(this,'left');

    if(l >= this.offsetWidth - slider_btn.offsetWidth)
    l = this.offsetWidth - slider_btn.offsetWidth;

    slider_btn.style.left = l + 'px';

    plan.style.width = slider_btn.offsetLeft + 'px';
}

// 全选，单选
function checkFn(){
    
    checkall.onclick = function(){

        for(var i = 0; i < checks.length; i++){

            checks[i].checked = this.checked;

        }
    }

    for(var i = 0; i < checks.length; i++){

        checks[i].onclick = isAllChecked;

    }
}

// 是否全选
function isAllChecked(){

    var flag = true;

    for(var i = 0; i < checks.length; i++){
        
        if(!checks[i].checked){
            flag = false;
            break;
        }

    }
    if(!checks.length) flag = false;
    checkall.checked = flag;
}

// 删除单个
function song_del(){

    for(var i = 0; i < song_del_one.length; i++){

        song_del_one[i].onclick = function(){

            this.parentNode.parentNode.remove();
            
            if(!tbody.children.length) {
                clear();
                return;
            };

            if(now >= tbody.children.length) now = tbody.children.length - 1; 

            if(!audio.pause){
                musicCut();
                isPlay();
                tbody.children[now].className = 'onPlay';

            }
            resPic();
            timeUpDate();
            isAllChecked();
            
        }
    }

}

// 删除选中
del_check.onclick = function(){

    

    var flag = true;

    for(var i = 0; i < checks.length; i++){
        if(checks[i].checked){
            
            flag = false;

            checks[i].parentNode.parentNode.remove();
            i--;

        }
    }

    if(!tbody.children.length) {
        clear();
        return;
    }

    if(flag) return;

    isAllChecked();
    if(now >= tbody.children.length) now = tbody.children.length - 1; 

    if(!audio.pause){
        musicCut();
        isPlay();
    }
    resPic();
    timeUpDate();
}

// 清空列表
clear_list.onclick = clear;

function clear(){
    tbody.innerHTML = '';
    isAllChecked();
    isEmpty();

}

// 播放
play.onclick = function(){

    if(audio.paused){

        audio.play();

        tbody.children[now].className = 'onPlay';

        song_tool_play[now].style.backgroundPosition = '-120px -200px';

    }else{

        audio.pause();

        tbody.children[now].className = '';

        song_tool_play[now].style.backgroundPosition = '-120px 0';

    }
    isPlay();
}

// 下一首
next.onclick = function(){

    song_tool_play[now].style.backgroundPosition = '-120px 0';

    ++now;
    if(now >= tbody.children.length) now = 0;
    musicCut();
    isPlay();
    resPic();
    timeUpDate();
    maskBg();
    nowPlayClass();

    song_tool_play[now].style.backgroundPosition = '-120px -200px';

}

// 上一首
prev.onclick = function(){

    song_tool_play[now].style.backgroundPosition = '-120px 0';

    --now;
    if(now < 0) now = tbody.children.length - 1;
    musicCut();
    isPlay();
    resPic();
    timeUpDate();
    maskBg();
    nowPlayClass();
    
    song_tool_play[now].style.backgroundPosition = '-120px -200px';

}

// 当前播放类名
function nowPlayClass(){

    for(var i = 0; i < tbody.children.length; i++){
        
        tbody.children[i].className = '';

    }

    tbody.children[now].className = 'onPlay';

}

// 切换歌曲src
function musicCut(){

    audio.src = tbody.children[now].getAttribute('data-src');

    audio.play();
}

// mask背景
function maskBg(){

    mask_pic[0].style.backgroundImage = `url(${tbody.children[now].getAttribute('data-pic')})`

}

// 切换播放图标
function isPlay(){
    if(audio.paused){

        play.style.backgroundPosition = '0 0';

    }else{

        play.style.backgroundPosition = '-30px 0';

    }
}

// 是否清空列表
function isEmpty(){

    var tbody = musicList.getElementsByTagName('tbody')[0]; // 歌曲列表

    if(!tbody.children.length){

        music_cur.innerHTML = '';

        music_detail.innerHTML = '<div class="poster"></div>';

        poster[0].style.backgroundImage = 'url(./pic/player_cover.png)';

        audio.src = '';
        
        play.onclick = null;

        next.onclick = null;

        prev.onclick = null;

        clear_list.onclick = null;
    }
}

// list点击播放
function listPlay(){

    for(var i = 0; i < song_tool_play.length; i++){
        
        song_tool_play[i].onclick = function(){

            var tr = this.parentNode.parentNode.parentNode;

            if(tr == tbody.children[now]){
                

                if(audio.paused){

                    audio.play();

                    this.style.backgroundPosition = '-120px -200px';

                    play.style.backgroundPosition = '-30px 0';

                    tr.className = 'onPlay';


                }else{
                    audio.pause();  

                    tr.className = '';

                    play.style.backgroundPosition = '0 0';

                    this.style.backgroundPosition = '-120px 0';

                }

            }else{

                tbody.children[now].className = '';

                tr.className = 'onPlay';

                audio.src = tr.getAttribute('data-src');

                audio.play();

                this.style.backgroundPosition = '-120px -200px';
                
                play.style.backgroundPosition = '-30px 0';

                song_tool_play[now].style.backgroundPosition = '-120px 0';

                for(var i = 0; i < tbody.children.length; i++){

                    if(tr == tbody.children[i]){

                        now = i;

                        break;
                    }

                }

            }


        }

    }
}

// 播放顺序
play_list.onclick = function(){
    playOrderIndex++;
    if(playOrderIndex >= playOrder.length) playOrderIndex = 0;
    this.style.backgroundPosition = playOrder[playOrderIndex];
}

// 点击红心
collect.flag = false;// 假设没有点击红心
collect.onclick = function(){

    if(this.flag){
        
        collect.style.backgroundPosition = '0 -96px';

    }else{

        collect.style.backgroundPosition = '-30px -96px';

    }
    this.flag = !this.flag;
}

// 纯净模式
state.flag = false;
state.onclick = function(){

    if(this.flag){

        this.style.backgroundPosition = '0 -282px';

    }else{

        this.style.backgroundPosition = '0 -311px';

    }

    this.flag = !this.flag;

}

// 点击音量图标
volume_icon.flag = false;//没有静音
volume_icon.onclick = function(){


    if(volume_icon.flag){
        // 打开
        this.style.backgroundPosition = '0 -144px';

        audio.volume = volmue_size;

        resVolmue();

    }else{
        //静音
        volmue_size = audio.volume;

        this.style.backgroundPosition = '0 -182px';

        audio.volume = 0;
        
        resVolmue();
    }
    volume_icon.flag = !volume_icon.flag;

}

// 刷新音量
function resVolmue(){

    var plan = volume_slider.getElementsByClassName('plan')[0];// 进度

    var l = audio.volume * (volume_slider.offsetWidth - volume_slider_btn.offsetWidth);

    plan.style.width = l + 'px';

    volume_slider_btn.style.left = l + 'px';
}
resVolmue();